# _*_ coding:utf-8 _*_
# @File  : daily_info.py
# @Time  : 2021-12-15  15:23
# @Author: zizle


# 每日开盘前的资讯
import time
import uuid
import datetime
import pathlib

from fastapi import APIRouter, Body, Query, Path
from pydantic import BaseModel

from db import FAConnection
from status import r_status
from configs import FILE_STORAGE

daily_info_api = APIRouter()


class ArticleItem(BaseModel):
    title: str
    category: str
    content: str


@daily_info_api.post('/infoarticle/', summary='资讯文章')
async def morning_message(article_item: ArticleItem = Body(...)):
    if article_item.category not in ['晨会纪要', '每日观察']:
        return {'code': r_status.VALIDATE_ERROR, 'message': '类型错误，上传失败!'}
    uuid_str = ''.join(str(uuid.uuid4()).split('-'))
    filename = str(int(time.time() * 1000)) + uuid_str + '.txt'
    month = datetime.datetime.today().strftime('%Y%m')
    middle_folder = pathlib.Path('INFORMATION/article/').joinpath(month)

    file_folder = pathlib.Path(FILE_STORAGE).joinpath(middle_folder)
    if not file_folder.exists():
        file_folder.mkdir(parents=True)
    filepath = file_folder.joinpath(filename)
    sql_filepath = (str(middle_folder) + '/' + filename).replace('\\', '/')
    # 生成txt文件数据
    with open(filepath, "w") as fp:
        fp.write(article_item.content)

    # 生成mysql数据记录，存储文件信息
    create_sql = 'INSERT INTO info_information_article (title,category,txt_file) ' \
                 'VALUES (%s,%s,%s);'
    params = [article_item.title, article_item.category, sql_filepath]
    db_conn = FAConnection(conn_name='生成信息文件记录')
    _, success = db_conn.insert(create_sql, param=params)
    if success:
        return {'code': r_status.SUCCESS, 'message': '上传成功!'}
    else:
        return {'code': r_status.SERVER_ERROR, 'message': '上传失败!'}


@daily_info_api.get('/infoarticle/', summary='资讯文章列表')
async def information_article(category: str = Query(...), page: int = Query(1, ge=1), page_size: int = Query(1, ge=1)):
    if not category:
        return {'code': r_status.VALIDATE_ERROR, 'message': '查询成功!', 'data': {}}
    start, offset = (page - 1) * page_size, page_size
    query_sql = 'SELECT SQL_CALC_FOUND_ROWS id,create_time,title,category,txt_file ' \
                'FROM info_information_article ' \
                'WHERE category=%s ORDER BY create_time DESC LIMIT %s,%s;'
    db_conn = FAConnection(conn_name='查询文章')
    ret = db_conn.paginator_query(query_sql, param=[category, start, offset], page=page, page_size=page_size)
    article_list = ret['records']
    for a in article_list:
        a['create_time'] = a['create_time'].strftime('%Y-%m-%d %H:%M:%S')
        del a['txt_file']
    return {'code': r_status.SUCCESS, 'message': '查询文章表成功!', 'data': ret}


@daily_info_api.get('/infoarticle/{article_id}/', summary='资讯文章的内容')
async def information_detail(article_id: int = Path(1, ge=1)):
    # 查询文章地址，读取返回
    sql = 'SELECT id,title,txt_file FROM info_information_article WHERE id=%s;'
    db_conn = FAConnection(conn_name='文章详情')
    article_obj = db_conn.query(sql, param=[article_id], fetchone=True)[0]
    if not article_obj:
        return {'code': r_status.NOT_CONTENT, 'success': '文章不存在!'}
    filepath = pathlib.Path(FILE_STORAGE).joinpath(article_obj['txt_file'])
    with open(filepath, 'r') as f:
        content = f.read()
    rep_data = {
        "id": article_id,
        "title": article_obj['title'],
        "content": content
    }
    return {'code': r_status.SUCCESS, 'message': '查询成功!', 'data': rep_data}
